package handlers

import (
	"encoding/json"
	"errors"
	"net/http"

	"zwai-app/config"
	"zwai-app/services"
	"zwai-app/util"
)

// registerRequest 前端传入的 JSON 结构
type registerRequest struct {
	Account    string `json:"account"`
	Username   string `json:"username"`
	Password   string `json:"password"`
	InviteCode string `json:"inviteCode,omitempty"`
	From       string `json:"from"`
	SMSCode    string `json:"smsCode"`
}

// registerResponse 成功时要返回的数据
type registerResponse struct {
	UserID     string `json:"userId"`
	InviteCode string `json:"inviteCode"`
}

// RegisterAuthRoutes 挂载 /register 路由
func RegisterAuthRoutes(mux *http.ServeMux) {
	mux.HandleFunc("/register", registerHandler)
}

func registerHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		util.JSONResponse(w, http.StatusMethodNotAllowed, map[string]interface{}{"code": 1, "msg": "只支持 POST 方法"})
		return
	}
	var req registerRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 2, "msg": "JSON 解析失败: " + err.Error()})
		return
	}

	// 必填字段检查
	if req.Account == "" || req.Username == "" || req.Password == "" || req.From == "" || req.SMSCode == "" {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 6, "msg": "手机号/用户名/密码/场景/验证码均不能为空"})
		return
	}

	// 万能验证码 222222 跳过校验
	if req.SMSCode != "222222" {
		platformCode, err := services.VerifyVolcengineSMSCode(req.Account, req.From, req.SMSCode)
		if err != nil {
			if platformCode == "" {
				platformCode = "7"
			}
			util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{
				"code": platformCode,
				"msg":  "验证码校验失败: " + err.Error(),
			})
			return
		}
	}

	userID, code, err := services.RegisterUser(r.Context(), req.Account, req.Username, req.Password, req.InviteCode)
	if err != nil {
		switch {
		case errors.Is(err, services.ErrAccountExists):
			util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 3, "msg": "账号已存在"})
		case errors.Is(err, services.ErrInvalidInviteCode):
			util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 4, "msg": "邀请码无效"})
		default:
			util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 5, "msg": "注册失败: " + err.Error()})
		}
		return
	}
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "注册成功", "data": registerResponse{UserID: userID.Hex(), InviteCode: code}})
}

// loginRequest 前端传入的 JSON 结构
type loginRequest struct {
	Account  string `json:"account"`
	Password string `json:"password"`
}

// loginResponse 登录成功返回
type loginResponse struct {
	Token string `json:"token"`
}

// RegisterLoginRoutes 注册 /login 路由
func RegisterLoginRoutes(mux *http.ServeMux, cfg config.Config) {
	mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			util.JSONResponse(w, http.StatusMethodNotAllowed, map[string]interface{}{"code": 1, "msg": "只支持 POST 方法"})
			return
		}
		var req loginRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 2, "msg": "JSON 解析失败: " + err.Error()})
			return
		}
		token, err := services.Login(r.Context(), req.Account, req.Password, cfg)
		if err != nil {
			if errors.Is(err, services.ErrInvalidCredentials) {
				util.JSONResponse(w, http.StatusUnauthorized, map[string]interface{}{"code": 3, "msg": "账号或密码错误"})
			} else {
				util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"code": 4, "msg": "登录失败: " + err.Error()})
			}
			return
		}
		util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "登录成功", "data": loginResponse{Token: token}})
	})
}
